﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.DataAccess.Common;
using T.FAS.Runtime.DataAccess.Kernel;
using Newtonsoft.Json.Linq;

namespace T.FAS.Runtime.DataAccess.Engine.ValidateChecker.Entity
{
    public class ValidateCheckRefItem : IValidateCheckItem
    {
        public IValidateCheckElement CheckElement { get; set; }
        public object InputValue { get; set; }
        public Dictionary<string, object> ExtInfo { get; set; }

        public ItemCheckResult Check()
        {
            ItemCheckResult result = new ItemCheckResult
            {
                Flag = false,
                Msg = new StringBuilder(),
            };
            string inputVal = InputValue?.ToString();
            if (string.IsNullOrEmpty(inputVal))
            {
                if (!CheckElement.IsAllowNull)
                {
                    result.Msg.Append("待校验输入值不能为空");
                    return result;
                }
                else
                {
                    result.Flag = true;
                    return result;
                }
            }
            if (CheckElement.IsReference)
            {
                try
                {
                    DataObject refObj;
                    if (EnvironmentSetting.RunningMode == RunningMode.LocalDebug)
                    {
                        refObj = TestTool.GetMetaData<DataObject>(CheckElement.RefObjectID);
                    }
                    else
                    {
                        refObj = RTPMetadataHelper.GetRTPMetadata(CheckElement.RefObjectID) as DataObject;
                    }
                    var table = refObj.LogicTableName;
                    var pk = refObj.GetPkColumn();
                    //DO查询逻辑
                    if (CheckElement.IsRefDataObject)
                    {
                        var sql = $"Select count(1) from {table} where {pk.ColumnName}='{inputVal}'";
                        var configKey = refObj.Database.GetDefaultConfigKey();
                        var db = DatabaseFactory.CreateDefaultDatabase();
                        var ds = db.GetData(configKey, sql, table);
                        var countStr = ds.Tables[0].Rows[0][0]?.ToString();
                        if (int.TryParse(countStr, out int count))
                        {
                            if (count == 0)
                            {
                                result.Flag = false;
                                result.Msg.Append($"CDO的DO列:{CheckElement.Name}的值:{inputVal}不存在，请检查");
                            }
                            else
                            {
                                result.Flag = true;
                            }
                            return result;
                        }
                    }
                    //SDO解析逻辑
                    else
                    {
                        var presetDataJson = refObj.PresetData?.Content;
                        if (!string.IsNullOrEmpty(presetDataJson))
                        {
                            var arr = JArray.Parse(presetDataJson);
                            var flag = false;
                            foreach (var item in arr)
                            {
                                if (item.Type == JTokenType.Object)
                                {
                                    var pkVal = ((JObject)item).GetValue(pk.ColumnName).ToString();
                                    if (string.Equals(pkVal, inputVal))
                                        flag = true;
                                }
                            }
                            if (flag)
                            {
                                result.Flag = true;
                            }
                            else
                            {
                                result.Msg.Append($"CDO的SDO列:{CheckElement.Name}的值:{inputVal}不存在，请检查");
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    result.Flag = false;
                    result.Msg.Append(e.Message);
                }
            }
            return result;
        }
    }
}
